package com.example.messengerapp.viewmodel


import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await

data class Profile(
    val name: String = "",
    val phone: String = ""
)

class ProfileViewModel : ViewModel() {

    private val _profile = MutableLiveData<Profile?>()
    val profile: MutableLiveData<Profile?> get() = _profile

    private val _phone = MutableLiveData<String>()
    val phone: LiveData<String> get() = _phone

    private val firestore = FirebaseFirestore.getInstance()
    private val auth = FirebaseAuth.getInstance()

    init {
        loadProfile()
    }

    private fun loadProfile() {
        viewModelScope.launch {
            val userId = auth.currentUser?.uid
            if (userId != null) {
                val profileDoc = firestore.collection("profiles").document(userId)
                try {
                    val snapshot = profileDoc.get().await()
                    val loadedProfile = snapshot.toObject(Profile::class.java)
                    if (loadedProfile != null) {
                        _profile.value = loadedProfile
                        _phone.value = loadedProfile.phone
                    }
                } catch (e: Exception) {
                    // Обработка ошибок
                }
            }
        }
    }

    private fun updateProfile(newProfile: Profile) {
        viewModelScope.launch {
            val userId = auth.currentUser?.uid
            if (userId != null) {
                val profileDoc = firestore.collection("profiles").document(userId)
                try {
                    profileDoc.set(newProfile).await()
                    _profile.value = newProfile
                    _phone.value = newProfile.phone
                } catch (e: Exception) {
                    // Обработка ошибок
                }
            }
        }
    }

    fun updatePhone(newPhone: String) {
        _phone.value = newPhone
        _profile.value = _profile.value?.copy(phone = newPhone)
        _profile.value?.let { updateProfile(it) }
    }
}
